package com.dwxt.sport.business.service;

import com.dwxt.common.base.StatusCode;
import com.dwxt.common.constant.VariableConstants;
import com.dwxt.common.util.SnowIdUtil;
import com.dwxt.sport.business.dao.FitnessSurveyEquipmentMapper;
import com.dwxt.sport.business.dao.FitnessSurveyMapper;
import com.dwxt.sport.business.entity.FitnessSurvey;
import com.dwxt.sport.business.entity.FitnessSurveyEquipment;
import com.dwxt.sport.business.vo.fitnessSurvey.InsertOrUpdateFitnessSurveyEquipmentVo;
import com.dwxt.sport.business.vo.fitnessSurvey.InsertOrUpdateFitnessSurveyVo;
import com.dwxt.sport.business.vo.fitnessSurvey.SelectFitnessSurveyVo;
import com.dwxt.sport.constant.CommonConstant;
import com.dwxt.sport.exception.CustomException;
import com.dwxt.sport.util.BusinessValidationUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

/**
 * 体质监测中心 Service
 *
 * @author Kuang.JiaZhuo
 * @date 2020-07-28 15:23
 */
@Service
public class FitnessSurveyService {

    @Resource
    FitnessSurveyMapper fitnessSurveyMapper;

    @Resource
    FitnessSurveyEquipmentMapper equipmentMapper;

    /**
     * @方法名：insertFitnessSurvey
     * @描述： 新增室体质监测中心
     * @作者： kjz
     * @日期： Created in 2020/7/28 15:56
     */
    @Transactional(rollbackFor = Exception.class)
    public int insertFitnessSurvey(InsertOrUpdateFitnessSurveyVo insertVo) {
        FitnessSurvey fitnessSurvey = new FitnessSurvey()
                .setId(SnowIdUtil.getInstance().nextId())
                .setCreateTime(LocalDateTime.now())
                .setIsDelete(VariableConstants.STRING_CONSTANT_0)
                .setStreetId(insertVo.getStreetId()) //街道id
                .setName(insertVo.getName()) //设备名称
                .setEquipmentsImgUrl(insertVo.getEquipmentsImgUrl()) //设备图片地址
                .setRecommendedCoverage(insertVo.getRecommendedCoverage()); //建议覆盖率
        return fitnessSurveyMapper.insert(fitnessSurvey);
    }

    /**
     * @方法名：updateFitnessSurvey
     * @描述： 更新体质监测中心
     * @作者： kjz
     * @日期： Created in 2020/7/28 16:09
     */
    @Transactional(rollbackFor = Exception.class)
    public int updateFitnessSurvey(InsertOrUpdateFitnessSurveyVo updateVo) {
        String id = updateVo.getId();
        if(!BusinessValidationUtil.verifyId(id)){
            throw new CustomException(StatusCode.ID_IS_NULL);
        }
        FitnessSurvey fitnessSurvey = new FitnessSurvey()
                .setUpdateTime(LocalDateTime.now())
                .setName(updateVo.getName()) //设备名称
                .setEquipmentsImgUrl(updateVo.getEquipmentsImgUrl()) //设备图片地址
                .setRecommendedCoverage(updateVo.getRecommendedCoverage()); //建议覆盖率

        if(null != updateVo.getStreetId()){
            fitnessSurvey.setStreetId(null);
        }

        return fitnessSurveyMapper.updateByPrimaryKeySelective(fitnessSurvey);
    }

    /**
     * @方法名：getFitnessSurveyByPage
     * @描述： 按条件查询体质监测中心列表(带分页)
     * @作者： kjz
     * @日期： Created in 2020/7/28 16:36
     */
    public PageInfo<FitnessSurvey> getFitnessSurveyByPage(SelectFitnessSurveyVo selectVo) {
        PageHelper.startPage(selectVo.getPageNum(), selectVo.getPageSize());
        List<FitnessSurvey> list = fitnessSurveyMapper.getFitnessSurveyByPage(selectVo);
        list.forEach(fitnessSurvey -> {
            fitnessSurvey.setEquipmentsImgUrl(CommonConstant.FILE_SERVER+fitnessSurvey.getEquipmentsImgUrl());
        });
        PageInfo<FitnessSurvey> pageInfo = new PageInfo(list);
        return pageInfo;
    }

    /**
     * @方法名：deleteFitnessSurveyByIds
     * @描述： 根据ids批量删除体质监测中心
     * @作者： kjz
     * @日期： Created in 2020/7/28 16:48
     */
    @Transactional(rollbackFor = Exception.class)
    public int deleteFitnessSurveyByIds(String ids) {
        if(ids == null || "".equals(ids)) {
            throw new CustomException(StatusCode.ID_IS_NULL);
        }
        String[] idArray = ids.split(",");

        return this.fitnessSurveyMapper.deleteFitnessSurveyByIds(idArray);
    }

    /**
     * @方法名：insertFitnessSurveyEquipment
     * @描述： 新增体质监测中心的设备关联
     * @作者： kjz
     * @日期： Created in 2020/7/29 10:12
     */
    @Transactional(rollbackFor = Exception.class)
    public int insertFitnessSurveyEquipment(InsertOrUpdateFitnessSurveyEquipmentVo insertVo) {

        String fitnessSurveyId = insertVo.getFitnessSurveyId();

        FitnessSurveyEquipment fitnessSurveyEquipment = new FitnessSurveyEquipment()
                .setId(SnowIdUtil.getInstance().nextId())
                .setCreateTime(LocalDateTime.now())
                .setIsDelete(VariableConstants.STRING_CONSTANT_0)
                .setFitnessSurveyId(fitnessSurveyId) //体质监测关联id
                .setEquipmentId(insertVo.getEquipmentId()) //设备id
                .setDeviceLocation(insertVo.getDeviceLocation()) //设备位置(暂时不确定是选择还是输入)
                .setSession(insertVo.getSession()) //使用频率(次/天)
                .setBuildingUse(insertVo.getBuildingUse()) //使用人次
                .setAvg(insertVo.getAverageUsageTime()) //平均使用时长
                .setTotalUsageTime(insertVo.getTotalUsageTime()) //使用总时长
                .setDeviceStates(insertVo.getDeviceStates()); //设备状态

        int result = equipmentMapper.insert(fitnessSurveyEquipment);

        if(result>0){
            this.updateFitnessSurveyById(fitnessSurveyId);
        }

        return result;
    }

    /**
     * @方法名：updateFitnessSurveyEquipment
     * @描述： 更新体质监测中心的关联设备信息
     * @作者： kjz
     * @日期： Created in 2020/7/29 10:38
     */
    @Transactional(rollbackFor = Exception.class)
    public int updateFitnessSurveyEquipment(InsertOrUpdateFitnessSurveyEquipmentVo updateVo) {
        String id = updateVo.getId();
        if(!BusinessValidationUtil.verifyId(id)){
            throw new CustomException(StatusCode.ID_IS_NULL);
        }
        FitnessSurveyEquipment fitnessSurveyEquipment = new FitnessSurveyEquipment()
                .setUpdateTime(LocalDateTime.now())
                .setFitnessSurveyId(null) //体质监测关联id
                .setEquipmentId(updateVo.getEquipmentId()) //设备id
                .setDeviceLocation(updateVo.getDeviceLocation()) //设备位置(暂时不确定是选择还是输入)
                .setSession(updateVo.getSession()) //使用频率(次/天)
                .setBuildingUse(updateVo.getBuildingUse()) //使用人次
                .setAvg(updateVo.getAverageUsageTime()) //平均使用时长
                .setTotalUsageTime(updateVo.getTotalUsageTime()) //使用总时长
                .setDeviceStates(updateVo.getDeviceStates()); //设备状态

        int result = equipmentMapper.updateByPrimaryKeySelective(fitnessSurveyEquipment);

        if(result>0){
            String fitnessSurveyId = equipmentMapper.selectByPrimaryKey(id).getFitnessSurveyId();
            this.updateFitnessSurveyById(fitnessSurveyId);
        }

        return result;
    }


    /**
     * @方法名：updateFitnessSurveyById
     * @描述： 新增或更新体质监测中心设备之后，更新体质中心需要统计的数据
     * @作者： kjz
     * @日期： Created in 2020/8/4 18:16
     */
    @Transactional(rollbackFor = Exception.class)
    public int updateFitnessSurveyById(String fitnessSurveyId) {
        HashMap map = equipmentMapper.selectStatisticsByHealthId(fitnessSurveyId);
        FitnessSurvey fitnessSurvey = new FitnessSurvey()
                .setAmount(Integer.valueOf(map.get("amount").toString()))
                .setEquipmentUsage(Integer.valueOf(map.get("equipmentUsage").toString()))
                .setAvg(Double.parseDouble(map.get("avgElapsedTime").toString()))
                .setUpdateTime(LocalDateTime.now())
                .setId(fitnessSurveyId);
        return fitnessSurveyMapper.updateByPrimaryKeySelective(fitnessSurvey);
    }

    /**
     * @方法名：getFitnessSurveyEquipmentByPage
     * @描述： 根据体质监测中心的id查询关联设备的列表(带分页)
     * @作者： kjz
     * @日期： Created in 2020/7/29 10:49
     */
    public PageInfo<FitnessSurveyEquipment> getFitnessSurveyEquipmentByPage(Integer pageNum, Integer pageSize, String fitnessSurveyId) {
        PageHelper.startPage(pageNum==null?1:pageNum, pageSize==null?10:pageSize);
        List<FitnessSurveyEquipment> list = equipmentMapper.selectFitnessSurveyEquipmenByFitnessSurveyId(fitnessSurveyId);
        PageInfo<FitnessSurveyEquipment> pageInfo = new PageInfo(list);
        return pageInfo;
    }

    /**
     * @方法名：deleteFitnessSurveyEquipmentByIds
     * @描述： 根据ids批量删除体质监测中心关联的设备
     * @作者： kjz
     * @日期： Created in 2020/7/29 10:57
     */
    @Transactional(rollbackFor = Exception.class)
    public int deleteFitnessSurveyEquipmentByIds(String ids) {
        if(ids == null || "".equals(ids)) {
            throw new CustomException(StatusCode.ID_IS_NULL);
        }
        String[] idArray = ids.split(",");

        int result = this.equipmentMapper.deleteFitnessSurveyEquipmentByIds(idArray);
        if(result>0){
            String id = idArray[0];
            String fitnessSurveyId = equipmentMapper.selectByPrimaryKey(id).getFitnessSurveyId();
            this.updateFitnessSurveyById(fitnessSurveyId);
        }
        return result;
    }
}
